import React, { useEffect, useState } from 'react'
import { ApproveBlock, Header } from '@components/ApprovePre/Approve'
import { awaitWrap } from '@src/assets/js/tool'
import { getTaskRequest } from './ajax'
import { message, Skeleton, List, Button } from 'antd'
import { useSelector } from 'react-redux'
import Task from './components/Task/Index'
import style from './Index.module.less'
import AddModal from './components/AddModal/Index'

async function initData (caseid, setTask, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getTaskRequest(caseid))
  setLoading(false)
  if (e !== null) {
    return message.warning(e.message)
  }
  if (d instanceof Array && d.length > 0) {
    setTask(d[0])
  }
}

function Main ({ caseDetail }) {
  const [task, setTask] = useState(null)
  const [feedback, setFeedback] = useState([])
  const [loading, setLoading] = useState(false)
  const [visible, setVisible] = useState(false)
  const userInfo = useSelector((state) => state.basic.userInfo)
  const [editable, setEditable] = useState(false)
  useEffect(() => {
    if (caseDetail) {
      initData(caseDetail.id, setTask, setLoading)
    }
  }, [caseDetail])
  useEffect(() => {
    if (task) {
      setFeedback(task.feedback || [])
    }
  }, [task])
  useEffect(() => {
    setEditable(userInfo && caseDetail && [userInfo.employeeid, userInfo.id].includes(caseDetail.processerid))
  }, [userInfo, caseDetail])
  return (
    <ApproveBlock>
      <AddModal visible={visible} task={task} caseDetail={caseDetail} hide={() => setVisible(false)} refreshFn={() => initData(caseDetail.id, setTask, setLoading)} />
      <Skeleton active loading={loading} style={{ margin: '0 24px' }}>
        <Header title='庭审笔录' />
        <List dataSource={task ? [task, ...feedback] : []} renderItem={(li, i) => <Task data={li} key={i} />} />
        {
          editable && (
            <div className={style['btn-line']}>
              <Button type='primary' onClick={() => setVisible(true)}>提交庭审笔录</Button>
            </div>
          )
        }
      </Skeleton>
    </ApproveBlock>
  )
}

export default Main
